<template>
	<div id="app">
		<button @click="showPemn">显示人员</button>
		<button @click="showPemn2">显示部门</button>
		<button @click="showPemn3">单选部门</button>
		<button @click="deleteData">删除人员</button>
		<button @click="deleteData2">删除部门</button>
		<!-- <a href="http://www.baidu.com">baidu</a> -->
		<SelectDep :data="sourceData" type="1" :show.sync="show3" @selected="selected3"></SelectDep>
		<SelectDep :data="sourceData" type="1" :show.sync="show2" @selected="selected2" multiple></SelectDep>
		<SelectDep :data="sourceData" type="2" :show.sync="show" @selected="selected" multiple :load="loadNode"></SelectDep>
		<span style="font-size:12px">{{ selectedData }}</span>
		<div class="empty_img" style="width:130px;height:130px"></div>
		<button @click="addLink('@范剑涛', 'http://www.baidu.com')">确定</button>
		<div
			class="zm-comment-edit"
			:id="contentId"
			contenteditable="true"
			data-slate-editor
			data-slate-node="value"
			suppresscontenteditablewarning
			autocorrect="true"
			role="textarea"
			autocapitalize="true"
			tabindex="0"
			@click="focusEl"
			placeholder="请输入"
			spellcheck="true"
			ref="edit_comment"
			@input="handelInpu"
			@keydown="keydownFn"
			@compositionend="compositionend"
			@compositionstart="compositionstart"
		>
			<span data-slate-node="element"
				><span id="text-0" data-slate-node="text"
					><span data-slate-leaf="true"
						><span data-slate-zero-width="n">&#xFEFF;<br /></span></span></span
			></span>
		</div>
	</div>
</template>
<script>
import cursor from "@/utils/cursor.utils";
import SelectDep from "@/components/selectDepartment/index";
import childData from "@/assets/childData.js";
import data from "@/assets/data";
let range = null;
let sel = null;
HTMLElement.prototype.isFocusable = function() {
	var current = document.activeElement;
	if (current === this) return true;
	var protectEvent = (e) => e.stopImmediatePropagation();
	this.addEventListener("focus", protectEvent, true);
	this.addEventListener("blur", protectEvent, true);
	this.focus({ preventScroll: true });
	var result = document.activeElement === this;
	this.blur();
	if (current) current.focus({ preventScroll: true });
	this.removeEventListener("focus", protectEvent, true);
	this.removeEventListener("blur", protectEvent, true);
	return result;
};
function saveSelection() {
	if (window.getSelection) {
		sel = window.getSelection();
		if (sel.getRangeAt && sel.rangeCount) {
			return sel.getRangeAt(0);
		}
	} else if (document.selection && document.selection.createRange) {
		return document.selection.createRange();
	}
	return null;
}

function restoreSelection(range) {
	if (range) {
		if (window.getSelection) {
			sel = window.getSelection();
			sel.removeAllRanges();
			sel.addRange(range);
		} else if (document.selection && range.select) {
			range.select();
		}
	}
}
export default {
	name: "App",
	components: {
		SelectDep,
	},
	data() {
		console.log(cursor);
		return {
			show: false,
			show2: false,
			contentId: "fanjiantao",
			show3: false,
			sourceData: [],
			selectedData: [],
			selectedData2: [],
			data: ["范剑涛", "小米", "小江"],
			showAt: false,
			savedRange: null,
			state: {
				focusNode: null,
				focusOffset: 0,
			},
		};
	},
	methods: {
		compositionend() {
			//console.log(cursor.getCursorNode());
		},
		compositionstart() {},
		getParentNode(cNode) {
			let leve = 1;
			let oNode = null;
			while (cNode && leve <= 4 && cNode !== this.$refs.edit_comment) {
				oNode = cNode;
				cNode = cNode.parentNode;
				leve++;
			}

			return oNode;
			// return flag
		},
		open() {
			const selection = window.getSelection();
			const range = selection?.getRangeAt(0);
			// 缓存光标所在节点
			state.focusNode = selection.focusNode;
			// 缓存光标所在节点位置
			state.focusOffset = selection.focusOffset;
			// 光标所在位置
			const pos = range.getBoundingClientRect();
			console.log(pos);
			// 显示选择框
			// 输入框失去焦点
			// refAtInput.value.blur()
			// 设置弹窗位置
			// nextTick(() => {
			//   const x = pos.x > 75 ? pos.x - 75 : 0
			//   const y = pos.y + pos?.height + 8
			// })
		},
		handelInpu(e) {
			console.log(e.target.innerHTML);
		},
		insertNode(node) {
			// 在内容中插入标签
			// 删掉选中的内容（如有）
			try {
				this.savedRange.deleteContents();
			} catch (error) {}

			// 插入链接
			this.savedRange.insertNode(node);
		},
		addBrNode() {
			let node = document.createElement("span");
			node.innerText = " ";
			this.insertNode(node);
			document.execCommand("enableObjectResizing", false, false);
			this.savedRange.collapse(false);
			range = saveSelection();
			restoreSelection(range);
		},
		addLink(text, url) {
			// 创建a标签
			let node = document.createElement("a");
			node.innerHTML = "<span>131312</span>";
			node.className = "atActive";
			node.setAttribute("contenteditable", "false");
			// node.href = url;
			node.target = "blank";
			this.insertNode(node);
			this.savedRange.collapse(false);
			// range=saveSelection();
			restoreSelection(this.savedRange);

			// this.addBrNode();
			// console.log()
		},
		keydownFn(event) {
			let e = event || window.event;

			if (e.keyCode == 8) {
				//  event.preventDefault();
				//  return false;
			}
			if (e.keyCode == "50" && e.key == "@") {
				// console.log(document.getSelection());
				// console.log(e.keyCode,"keyCode");
			}
			if (e.keyCode == "13") {
				//  range.setStart(startNode, startOffset);
			}
		},
		focusEl(e) {
			// console.log(e.target)
			//event.target.blur();
			// console.log(e.target.tagName)
			if (e.target.tagName.toLowerCase() == "a") {
				sel = window.getSelection();
				sel.removeAllRanges();
				// restoreSelection(range);
				// document.getElementById()
			}

			return false;
		},
		saveSelection() {
			//保存光标位置
			if (window.getSelection) {
				sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					return sel.getRangeAt(0);
				}
			} else if (document.selection && document.selection.createRange) {
				return document.selection.createRange();
			}
			return null;
		},
		restoreSelection(range) {
			//恢复光标位置
			if (range) {
				if (window.getSelection) {
					sel = window.getSelection();
					sel.removeAllRanges();
					sel.addRange(range);
				} else if (document.selection && range.select) {
					range.select();
				}
			}
		},
		showPemn() {
			if (this.sourceData.length > 0) {
				this.show = true;
				return;
			}
			$api.companyDepartments().then((res) => {
				this.sourceData = res.data;
				this.show = true;
				//console.log(res);
				// $api.getDeps().then(res=>{
				//   //console.log(res.data);
				//   this.sourceData[0].children=res.data;
				//   console.log(this.sourceData);
				// });
			});
		},
		showPemn2() {
			this.show2 = true;
			if (this.sourceData.length > 0) {
				return;
			}
			setTimeout(() => {
				this.sourceData = data.slice(0);
			}, 500);
		},
		showPemn3() {
			this.show3 = true;
			if (this.sourceData.length > 0) {
				return;
			}
			setTimeout(() => {
				this.sourceData = data.slice(0);
			}, 500);
		},
		deleteData() {
			this.selectedData.splice(0, 1);
		},
		deleteData2() {
			this.selectedData2.splice(0, 1);
		},

		selected(v) {
			this.selectedData = v;
			console.log(v);
		},
		selected2(v) {
			this.selectedData2 = v;
			console.log(v);
		},
		selected3(v) {
			this.selectedData3 = v;
		},
		loadNode(item, resolve) {
			// console.log(item);
			$api.getChildUser(item.F_DepartmentId, item.F_CompanyId, item.Keyword).then((res) => {
				resolve(res.data.Rows);
			});
		},
		selectHandler() {
			// 监听选定文本的变动
			let sel = window.getSelection();
			let range = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
			if (range && range.commonAncestorContainer.ownerDocument.activeElement.id === this.contentId) {
				console.log(range);
				// console.log(range);
				this.savedRange = range;
				// if(range.commonAncestorContainer.parentNode.tagName.toLowerCase()=="a"){
				//      this.savedRange.collapse(true);
				// }
			}
		},
	},
	mounted() {
		document.addEventListener("selectionchange", this.selectHandler);
		// const callback = function(mutationsList, observer) {
		//     // Use traditional 'for loops' for IE 11
		//     for(let mutation of mutationsList) {
		//         if (mutation.type === 'childList') {

		//             if(mutation.removedNodes.length>0){
		//                   console.log("删除Dom");
		//             }else{
		//                 console.log("添加Dom");
		//             }
		//         }
		//     }
		// };
		// const observer = new MutationObserver(callback);
		// observer.observe(this.$refs.edit_comment, { attributes: false, childList: true, subtree: false });

		// $api.companyDepartments().then(res=>{
		//    console.log(res);
		// });
		//  console.log($commonApi,$api)
	},
};
</script>

<style lang="less">
.zm-comment-edit {
	outline: none;
	width: 400px;
	margin: auto;
	background: #fafafa;
	padding: 10px;
	border-radius: 4px;
	font-size: 14px;
	border: solid 1px #eee;
	outline: none;
	user-select: text;
	white-space: pre-wrap;
	height: 100px;
	overflow: auto;
	overflow-wrap: break-word;
	line-height: 18px;
	line-height: 1.5;
	& * {
		box-sizing: border-box;
		margin: 0;
		outline: none;
		padding: 0;
	}

	// -webkit-user-modify: read-write-plaintext-only;
	.primary {
		color: blue;
	}
	.atActive {
		cursor: pointer;
		z-index: 1;
		margin-right: 5px;
		// display:inline-block;
		color: red;
	}
	span {
		font-size: 15px;
	}
	span[data-query="@"] {
		color: blue;
		pointer-events: none;
		display: inline-block;
	}
	span[data-text] {
		color: black;
		display: inline-block;
	}
}
</style>
